/**
 * Created by Kuballle on 10/25/2014.
 */
angular.module('CiulApp', ['facebook'])

    .config([
        'FacebookProvider',
        function(FacebookProvider) {
            var myAppId = '758110410904505';

            // You can set appId with setApp method
            // FacebookProvider.setAppId('myAppId');

            /**
             * After setting appId you need to initialize the module.
             * You can pass the appId on the init method as a shortcut too.
             */
            FacebookProvider.init(myAppId);

        }
    ])

    .controller('MainController', [
        '$scope',
        '$timeout',
        'Facebook',
        function($scope, $timeout, Facebook) {

            var accessToken = '';

            // Define user empty data :/
            $scope.user = {};
            $scope.friends = {};
            $scope.photos = {};

            // Defining user logged status
            $scope.logged = false;

            // And some fancy flags to display messages upon user status change
            $scope.byebye = false;
            $scope.salutation = false;

            /**
             * Watch for Facebook to be ready.
             * There's also the event that could be used
             */
            $scope.$watch(
                function() {
                    return Facebook.isReady();
                },
                function(newVal) {
                    if (newVal)
                        $scope.facebookReady = true;
                }
            );

            var userIsConnected = false;

            Facebook.getLoginStatus(function(response) {
                if (response.status == 'connected') {
                    userIsConnected = true;
                }else if (response.status == 'not_authorized') {
                    console.log('not authorized');
                }else { // not login
                    console.log('not login');
                }
            });

            /**
             * IntentLogin
             */
            $scope.IntentLogin = function() {
                if(!userIsConnected) {
                    $scope.login();
                }
            };

            /**
             * Login
             */
            $scope.login = function() {
                Facebook.login(function(response) {
                    if (response.status == 'connected') {
                        accessToken = response.authResponse.accessToken;
                        $scope.logged = true;
                        $scope.me();
//                        $scope.getFriends();
                        $scope.getPhotos();
                    }
                }, {scope: 'email,user_likes,user_photos,user_friends,read_friendlists'});
            };

            /**
             * me
             */
            $scope.me = function() {
                Facebook.api('/me', function(response) {
                    /**
                     * Using $scope.$apply since this happens outside angular framework.
                     */
                    $scope.$apply(function() {
                        $scope.user = response;
                    });

                });
            };

            /**
             * friends
             */
            $scope.getFriends = function() {
                Facebook.api('/me/taggable_friends', 'GET', {fields: 'id, name'}, function(response) {
                    $scope.$apply(function() {
                        $scope.friends = response;
                    });

                });
            };

            /**
             * friends
             */
            $scope.getPhotos = function() {
                Facebook.api('/me/albums', 'GET', {fields: 'id'}, function(albumsResponse) {
                    for(var i=0; i<albumsResponse.data.length; i++){
                    console.log(albumsResponse.data[i].id);
                        Facebook.api('/'+albumsResponse.data[i].id+'/photos', 'GET', {fields: 'id,images'}, function(photosResponse){
                            $scope.$apply(function() {
                                $scope.photos = photosResponse;
                            });

                        });
                    }
//                    $scope.photos = 'https://graph.facebook.com/v2.1/'+albumsResponse.data[0].id+'/photos?access_token='+accessToken+'&pretty=0&fields=id&limit=20';
                });
            };

            /**
             * Logout
             */
            $scope.logout = function() {
                Facebook.logout(function() {
                    $scope.$apply(function() {
                        $scope.user   = {};
                        $scope.friends = {};
                        $scope.photos = {};
                        $scope.logged = false;
                    });
                });
            }

            /**
             * Taking approach of Events :D
             */
            $scope.$on('Facebook:statusChange', function(ev, data) {
                console.log('Status: ', data);
                if (data.status == 'connected') {
                    $scope.$apply(function() {
                        $scope.salutation = true;
                        $scope.byebye     = false;
                    });
                } else {
                    $scope.$apply(function() {
                        $scope.salutation = false;
                        $scope.byebye     = true;

                        // Dismiss byebye message after two seconds
                        $timeout(function() {
                            $scope.byebye = false;
                        }, 2000)
                    });
                }


            });


        }
    ])

/**
 * Just for debugging purposes.
 * Shows objects in a pretty way
 */
    .directive('debug', function() {
        return {
            restrict:	'E',
            scope: {
                expression: '=val'
            },
            template:	'<pre>{{debug(expression)}}</pre>',
            link:	function(scope) {
                // pretty-prints
                scope.debug = function(exp) {
                    return angular.toJson(exp, true);
                };
            }
        }
    })

;

